package com.hu.biz.util.socket;


import com.hu.common.constants.SocketResponseMessageContract;
import com.hu.common.domain.dto.SocketMessageDTO;
import com.hu.common.exception.BizException;

import com.hu.common.util.adm.Assert;
import com.hu.common.util.adm.E2s;
import com.hu.common.util.adm.ObjectParser;
import io.netty.channel.Channel;
import io.netty.channel.group.ChannelGroup;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @ClassName SocketMessageDecode
 * @Description socket通讯工具类
 * @author 355760
 **/
public class SocketMessageUtil {
    private final static Logger logger = LoggerFactory.getLogger(SocketMessageUtil.class);

    public static SocketMessageDTO decode(String request) throws Exception {
        return ObjectParser.parse(request, SocketMessageDTO.class);
    }

    public static String encode(SocketMessageDTO response) throws Exception {
        return ObjectParser.toJson(response);
    }

    /**
     * 通过channel发送消息
     * @param channel channel
     * @param body 消息体
     */
    public static void sendByChannel(Channel channel, SocketMessageDTO body) {
        try {
            String json = encode(body);
            channel.writeAndFlush(new TextWebSocketFrame(json));
        } catch (Exception e) {
            logger.error("[Websocket:] sendByChannel exception: {}", E2s.exception2String(e));
        }
    }

    public static void sendAllChannel(SocketMessageDTO body) {
        try {
            String json = encode(body);
            ChannelGroup channelGroup = WebSocketChannelManager.getChannelGroup();
            channelGroup.writeAndFlush(new TextWebSocketFrame(json));
        } catch (Exception e) {
            logger.error("[Websocket:] sendAllChannel exception: {}", E2s.exception2String(e));

        }
    }

    /**
     * 解析消息
     * @param request 消息源数据
     * @return SocketMessageDTO
     */
    public static SocketMessageDTO parseRequest(String request) {
        SocketMessageDTO requestDTO;
        try {
            requestDTO = decode(request);
        } catch (Exception e) {
            throw new BizException(SocketResponseMessageContract.INVALID_REQ_ARG);
        }

        if (Assert.isEmpty(requestDTO.getHeader())) {
            String msg = String.format(SocketResponseMessageContract.MISS_REQ_ARG, "header");
            throw new BizException(msg);
        }
        return requestDTO;
    }
}
